import { Button, Popup, SelectBox } from 'devextreme-react';
import DataGrid from 'devextreme-react/data-grid';
import notify from 'devextreme/ui/notify';
import React, { useCallback, useImperativeHandle, useRef, useState } from 'react';
import { useModel } from 'umi';
import { InvAgeConfigItem } from '../../type';
import { columnsMonth, columnsYear } from './devDataGird';
import './index.less';
import { getInvAgeConfig, updateInvAgeConfig } from './service';

// 按月
const defaultM = ['M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'M8', 'M9', 'M10', 'M11', 'M12'];

// 按季度
const defaultQ = ['Q1', 'Q2', 'Q3', 'Q4'];

// 按半年
const defaultHY = ['HY1', 'HY2'];

// 年度
const defaultY = ['Y1', 'Y2', 'Y3', 'Y4', 'Y5', 'Y6', 'Y7', 'Y8', 'Y9', 'Y10'];

//
const rightSelectSource = [
  {
    displayName: '1年期',
    range: ['Y1', 'Y2'],
  },
  {
    displayName: '2年期',
    range: ['Y1', 'Y3', 'Y4'],
  },
  {
    displayName: '3年期',
    range: ['Y1', 'Y3', 'Y5', 'Y6'],
  },
  {
    displayName: '4年期',
    range: ['Y1', 'Y3', 'Y5', 'Y7', 'Y8'],
  },
  {
    displayName: '5年期',
    range: ['Y1', 'Y3', 'Y5', 'Y7', 'Y9', 'Y10'],
  },
];

const AgeConfigButton = React.forwardRef((props: any, ref: any) => {
  const { reloadDevTable } = props;
  const { initialState } = useModel('@@initialState');
  const { dbname } = (initialState?.curPart as API.CurPart) || {};
  const [visible, setVisible] = useState<boolean>(false);
  const popupRef = useRef<any>(null);
  const refsDevLeft = useRef<any>(null);
  const refsDevRight = useRef<any>(null);
  // const eventsSaveData = useRef<any>([]);
  const [selectedLeftData, setSelectedLeftData] = useState<any[]>([]);
  const [selectedRightData, setSelectedRightData] = useState<any[]>([]);
  const [reviewState, setReviewState] = useState<number>(999);
  const [colYearData, setColYearData] = useState<any[]>([]);
  const [colMonthData, setMonthData] = useState<any[]>([]);

  const [leftValue, setLeftValue] = useState<any>('半年');
  const [rightValue, setRightValue] = useState<any>('3年期');

  const getDataList = useCallback(async () => {
    const res: any = await getInvAgeConfig({
      dbname,
    });
    if (res.success) {
      let yearData = [],
        monthData = [],
        yearKey: any[] = [],
        monthKey = [];
      const data = Array.isArray(res?.data) ? res.data : [];
      if (data.length > 0) {
        yearData = data.filter((item: InvAgeConfigItem) => {
          return item.fieldName.startsWith('Y');
        });

        monthData = data.filter((item: InvAgeConfigItem) => {
          return !item.fieldName.startsWith('Y');
        });

        yearKey = yearData
          .filter((item: InvAgeConfigItem) => {
            return item.isShow;
          })
          .map((item: InvAgeConfigItem) => item.fieldName);

        monthKey = monthData
          .filter((item: InvAgeConfigItem) => {
            return item.isShow;
          })
          .map((item: InvAgeConfigItem) => item.fieldName);
      }
      setSelectedRightData(yearKey);
      setSelectedLeftData(monthKey);
      setColYearData(yearData);
      setMonthData(monthData);
      // 一年内选择
      if (monthKey.includes('M1')) {
        setLeftValue('月度');
      }
      if (monthKey.includes('Q1')) {
        setLeftValue('季度');
      }
      if (monthKey.includes('HY1')) {
        setLeftValue('半年');
      }
      // 年度选择

      for (const rightItem of rightSelectSource) {
        const str = rightItem.displayName.split('年期')[0];
        const range = rightItem.range;
        if (
          range.length === yearKey.length &&
          yearKey.every((item) => item === range.includes(item))
        ) {
          setRightValue(rightItem.displayName);
          break;
        }
      }
    }
  }, []);

  // 自定义方法
  useImperativeHandle(ref, () => ({
    showPupop: async () => {
      await getDataList();
      setVisible(true);
      setReviewState(999);
    },
  }));

  const onCancel = () => {
    setVisible(false);
    setReviewState(999);
    setSelectedLeftData([]);
    setSelectedRightData([]);
  };

  const findData = (newData: any[], strKey: string) => {
    const isTrue = newData.find((itemF: any) => itemF === strKey);
    return isTrue;
  };

  const onOk = async () => {
    if (refsDevLeft.current) {
      if (selectedLeftData.length === 0 && selectedRightData.length === 0) {
        return notify(`请选择库龄区间`, 'warning', 2000);
      }
      const refsGridLeft = refsDevLeft.current.instance;
      const leftGetDataSource = refsGridLeft.getDataSource();
      const leftData = leftGetDataSource._items.map((item: any) => {
        item.rowState = 'update';
        item.where = { fieldName: item.fieldName };
        const newKey = findData(selectedLeftData, item.fieldName);
        item.isShow = newKey ? true : false;
        return item;
      });

      const refsGridRight = refsDevRight.current.instance;
      const rightGetDataSource = refsGridRight.getDataSource();
      const rightData = rightGetDataSource._items.map((item: any) => {
        item.rowState = 'update';
        item.where = { fieldName: item.fieldName };
        const newKey = findData(selectedRightData, item.fieldName);
        item.isShow = newKey ? true : false;
        return item;
      });
      const yearAndMonth = [...rightData, ...leftData];
      notify(`库龄设置成功！`, 'success', 2000);
      const res = await updateInvAgeConfig(dbname, yearAndMonth);
      if (res.success) {
        onCancel();
        notify(`库龄设置成功！`, 'success', 2000);
        reloadDevTable();
      } else {
        notify(`库龄设置失败！${res.data}`, 'error', 2000);
      }
    }
  };

  const changeSelLeft = (keySel: any) => {
    if (keySel === '月度') {
      setSelectedLeftData(defaultM);
    } else if (keySel === '季度') {
      setSelectedLeftData(defaultQ);
    } else if (keySel === '半年') {
      setSelectedLeftData(defaultHY);
    } else {
      setSelectedLeftData(defaultHY);
      setSelectedRightData(rightSelectSource[2].range);
    }
  };
  const changeSelRight = (selectedItem: any) => {
    const keySel = selectedItem?.displayName;
    const range = selectedItem?.range;
    if (keySel) {
      setSelectedRightData(range);
    } else {
      setSelectedLeftData(defaultHY);
      setSelectedRightData(rightSelectSource[2].range);
    }
  };

  const onSelectionChangedLeft = useCallback((e: any) => {
    console.log(`🚀--Nice ~ onSelectionChangedLeft ~ e:`, e);
    e.component.cancelEditData();
    setSelectedLeftData(e.selectedRowKeys);
  }, []);

  const onSelectionChangedRight = useCallback(({ selectedRowKeys }: any) => {
    setSelectedRightData(selectedRowKeys);
  }, []);

  return (
    <>
      {visible && (
        <Popup
          ref={popupRef}
          visible={visible}
          title={'库龄段设置'}
          wrapperAttr={{
            class: "fix-popup-title-width"
          }}
          // titleRender={(params: any) => {
          //   return (
          //     <div
          //       style={{
          //         display: 'flex',
          //         justifyContent: 'space-between',
          //         alignItems: 'center',
          //       }}
          //     >
          //       <h5>库龄段设置</h5>
          //       {/* <Button
          //         icon="close"
          //         stylingMode="text"
          //         onClick={() => onCancel()}
          //         style={{ marignRight: '-12px' }}
          //       ></Button> */}
          //     </div>
          //   );
          // }}
          {...props}
          width={600}
          height={600}
          // dragOutsideBoundary={true}
          resizeEnabled={true}
          onHiding={() => onCancel()}
          toolbarItems={[
            {
              widget: 'dxButton',
              toolbar: 'bottom',
              location: 'before',
              size: 'small',
              options: {
                text: '恢复默认',
                onClick: () => {
                  setLeftValue('半年');
                  setRightValue('3年期');
                  changeSelLeft('半年');
                  changeSelRight('3年期');
                },
              },
            },
            {
              widget: 'dxButton',
              toolbar: 'bottom',
              location: 'after',
              size: 'small',
              options: {
                text: '取消',
                onClick: () => onCancel(),
              },
            },
            {
              widget: 'dxButton',
              toolbar: 'bottom',
              location: 'after',
              size: 'small',
              options: {
                text: '确定',
                type: 'default',
                onClick: () => onOk(),
              },
            },
          ]}
          contentRender={() => (
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                border: '2px solid #e3e3e3',
                borderRadius: 5,
              }}
            >
              <div style={{ borderRight: '2px solid #e3e3e3', flex: 1 }}>
                <div
                  style={{
                    margin: '10px 10px 10px 10px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                  }}
                >
                  <div style={{ lineHeight: '32px' }}>一年以内区间设置</div>
                  <SelectBox
                    width={80}
                    items={[
                      {
                        displayName: '半年',
                      },
                      {
                        displayName: '季度',
                      },
                      {
                        displayName: '月度',
                      },
                    ]}
                    displayExpr="displayName"
                    valueExpr="displayName"
                    value={leftValue}
                    onSelectionChanged={(e: any) => {
                      setLeftValue(e.selectedItem.displayName);
                      changeSelLeft(e.selectedItem.displayName);
                    }}
                  />
                </div>
                <DataGrid
                  className="PaperDevSortableGrid devHeadersCenter"
                  ref={refsDevLeft}
                  height={400}
                  dataSource={colMonthData}
                  keyExpr="fieldName"
                  defaultColumns={columnsMonth}
                  showBorders={false}
                  showRowLines={true}
                  showColumnLines={false}
                  repaintChangesOnly={true}
                  scrolling={{ mode: 'standard' }}
                  selectedRowKeys={selectedLeftData}
                  showColumnHeaders={false}
                  editing={{
                    allowAdding: false,
                    allowDeleting: false,
                    allowUpdating: false,
                  }}
                  selection={{
                    mode: 'multiple',
                    // selectAllMode: 'allPages',
                    showCheckBoxesMode: 'always',
                  }}
                  // onSelectionChanged={onSelectionChangedLeft}
                  // onSaved={saveDataLeft}
                >
                  {/* <Editing mode="cell" allowUpdating={true} startEditAction="dblClick" /> */}
                </DataGrid>
              </div>

              <div style={{ flex: 1 }}>
                <div
                  style={{
                    margin: '10px 10px 10px 10px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                  }}
                >
                  <div style={{ lineHeight: '32px' }}>年区间设置</div>
                  <SelectBox
                    width={100}
                    items={rightSelectSource}
                    displayExpr="displayName"
                    valueExpr="displayName"
                    value={rightValue}
                    onSelectionChanged={(e: any) => {
                      setRightValue(e.selectedItem.displayName);
                      changeSelRight(e.selectedItem);
                    }}
                  />
                </div>
                <DataGrid
                  className="PaperDevSortableGrid devHeadersCenter"
                  ref={refsDevRight}
                  dataSource={colYearData}
                  keyExpr="fieldName"
                  defaultColumns={columnsYear}
                  showBorders={false}
                  showRowLines={true}
                  showColumnLines={false}
                  repaintChangesOnly={true}
                  scrolling={{ mode: 'standard' }}
                  showColumnHeaders={false}
                  selectedRowKeys={selectedRightData}
                  editing={{
                    allowAdding: false,
                    allowDeleting: false,
                    allowUpdating: false,
                  }}
                  selection={{
                    mode: 'multiple',
                    // selectAllMode: 'allPages',
                    showCheckBoxesMode: 'always',
                  }}
                  // onSelectionChanged={onSelectionChangedRight}
                  // onSaved={saveDataRight}
                >
                  {/* <Editing mode="cell" allowUpdating={true} startEditAction="dblClick" /> */}
                </DataGrid>
              </div>
            </div>
          )}
        />
      )}
    </>
  );
});

export default AgeConfigButton;
